package MapEditor;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.doge.Settings;
import com.doge.Tile;

public class EditorFileOperations 
{
	//TODO: make Tile and required classes seralizable
	public static void SaveMapToFile(String mapPath, 
									List<GridSquare> tiles, 
									List<String> textureLocations) throws Exception
	{
		//only works on desktop 
		//SAVES TO DOGE-DESKTOP/BIN/DATA/MAPS
		PrintWriter writer = new PrintWriter(Gdx.files.internal("./bin/data/maps/"+mapPath).file(), 
											"UTF-8");
		
		for(String a : textureLocations)
		{
			writer.print(a+";");
		}
		
		writer.println();

		for(GridSquare t : tiles)
		{
			writer.print(t.t.tileEntry_num
						+","+t.t.borderTile  
						+","+t.t.x         
						+","+t.t.y
						+","+(t.t.character == null ?"null" : t.t.character.name)
						+","
						);
			
			//if(t.textureIds.size() == 0)
			//	writer.print("null");
			//else
				for(int a : t.textureIds)
				{
					writer.print(a+",");
				}
			
			writer.print(";");
		}
		writer.println();
		
		writer.flush();
		writer.close();
	}
	
	public static Tile[][] LoadMapFromFile(String mapPath) throws Exception
	{
		BufferedReader reader = new BufferedReader(new FileReader(Gdx.files.internal("./bin/data/maps/"+mapPath).file()));
		Tile[][] tiles = new Tile[Settings.mapDim][Settings.mapDim];	
		ArrayList<String> textures = new ArrayList<String>(
								Arrays.asList(reader.readLine().split(";"))); 
		
		for(String a : reader.readLine().split(";"))
		{
			String[] b = a.split(",");
			Tile t = new Tile(null);
			
			t.setCollision(Integer.parseInt(b[0]));
			t.borderTile  = (b[1].toLowerCase().compareTo("true") == 0 ? true : false);
			t.x = Integer.parseInt(b[2]);
			t.y = Integer.parseInt(b[3]);

			if(b[4].compareTo("null") != 0)
			{
				Class<?> c = Class.forName(("enemies."+b[4]).replaceAll("\\s+",""));
				java.lang.reflect.Constructor<?> constructor = c.getConstructor(Tile.class);	
				t.character = (com.doge.Character)constructor.newInstance(new Object[]{t});

				t.occupied = true;
			}
			
			for(int i = 5; i < b.length; ++i)
				t.addTexture(new TextureRegion(
								new Texture("./bin/"+
									textures.get(Integer.parseInt(b[i])))));

				tiles[t.x][t.y] = t;//new GridSquare(t);	
		}
		
		reader.close();
		return tiles;
	}
}
